from pyramid.config import Configurator
from pyramid.session import SignedCookieSessionFactory
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy

from sqlalchemy import engine_from_config
from .models import DBSession, Base
from .security import SecurityPolicy


def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    my_session_factory = SignedCookieSessionFactory('itsaseekreet', timeout=3600)  # 设置临时会话

    config = Configurator(settings=settings, session_factory=my_session_factory, root_factory='.resources.Root')

    # 设置认证和授权策略
    # authn_policy = AuthTktAuthenticationPolicy('sosecret')
    # authz_policy = ACLAuthorizationPolicy()

    config.set_security_policy(
        SecurityPolicy(
            secret=settings['app.secret'],
        ),
    )

    config.include('pyramid_jinja2')
    config.include('.routes')
    config.add_jinja2_renderer(".html")

    config.scan('.views')
    return config.make_wsgi_app()

    # 添加自定义中间件
    # app = config.make_wsgi_app()
    # app = CustomMiddleware(app)
    # return app
